//
//  appRunInBackground.m
//  ScreenRecord_ios_oc
//
//  Created by 51talk on 2021/5/28.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

//#import <BackgroundTasks/BackgroundTasks.h>
//#import <PushKit/PushKit.h>


#import "appRunInBackground.h"

@interface AppRunInBackground()

@property (nonatomic, assign) UIBackgroundTaskIdentifier backgroundTaskIdentifier;
@property (nonatomic, strong) NSTimer *timerAD;
@property (nonatomic, strong) NSTimer *timerTick;
@property (nonatomic,strong) AVAudioPlayer *playerBack;

@end

static AppRunInBackground *Instance;

@implementation AppRunInBackground {
    CFRunLoopRef _runloopRef;
    dispatch_queue_t _queue;
}

+ (AppRunInBackground *) getInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!Instance) {
            Instance = [[AppRunInBackground alloc] init];
        }
    });
    return Instance;
}

- (instancetype)init {
    if (self = [super init]) {
        [self setupAudioSession];
//        _queue = dispatch_queue_create("com.audio.inBackground", NULL);
        //静音文件
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"SomethingJustLikeThis" ofType:@"mp3"];
        NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
        self.playerBack = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
        [self.playerBack prepareToPlay];
        // 0.0~1.0,默认为1.0
//        self.playerBack.volume = 0.01;
        // 循环播放
        self.playerBack.numberOfLoops = -1;
    }
    return self;
}

- (void)stopBGRun{
    NSLog(@"stopBGRun");
//    if (self.timerAD) {
//        CFRunLoopStop(_runloopRef);
//        // 关闭定时器即可
//        [self.timerAD invalidate];
//        self.timerAD = nil;
//        [self.timerTick invalidate];
//        self.timerTick = nil;
//        [self.playerBack stop];
//    }
    
    [self.playerBack stop];
//    if (self.backgroundTaskIdentifier) {
//        NSLog(@"stopRun endBackgroundTask");
//        [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];
//        self.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
//    }
}

- (void)startBGRun {
    NSLog(@"startBGRun");
    [self.playerBack play];
//    [self applyforBackgroundTask];
    
    ///确保两个定时器同时进行
//    dispatch_async(_queue, ^{
//        self.timerAD = [[NSTimer alloc] initWithFireDate:[NSDate date] interval:60.0 target:self selector:@selector(listenBG) userInfo:nil repeats:YES];
//        self.timerTick = [[NSTimer alloc] initWithFireDate:[NSDate date] interval:1.0 target:self selector:@selector(onTick) userInfo:nil repeats:YES];
//        self->_runloopRef = CFRunLoopGetCurrent();
//        [[NSRunLoop currentRunLoop] addTimer:self.timerAD forMode:NSDefaultRunLoopMode];
//        [[NSRunLoop currentRunLoop] addTimer:self.timerTick forMode:NSDefaultRunLoopMode];
//
//        CFRunLoopRun();
//    });
}

- (void)onTick {
    NSLog(@"dida dida");
}

- (void)setupAudioSession {
    // 新建AudioSession会话
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    // 设置后台播放
    NSError *error = nil;
    [audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&error];
    if (error) {
        NSLog(@"Error setCategory AVAudioSession: %@", error);
    }
    NSLog(@"%d", audioSession.isOtherAudioPlaying);
    NSError *activeSetError = nil;
    // 启动AudioSession，如果一个前台app正在播放音频则可能会启动失败
    [audioSession setActive:YES error:&activeSetError];
    if (activeSetError) {
        NSLog(@"Error activating AVAudioSession: %@", activeSetError);
    }
}

- (void)applyforBackgroundTask{
    self.backgroundTaskIdentifier =[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"task end normal");
            [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];
            self.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
        });
    }];
}

- (void)listenBG{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"remaining:%lld", (long long int)([[UIApplication sharedApplication] backgroundTimeRemaining]));
        if ([[UIApplication sharedApplication] backgroundTimeRemaining] < 61.0) {
            NSLog(@"后台快被杀死了");
//            [self.playerBack play];
//            [self applyforBackgroundTask];
        }
        else{
            NSLog(@"后台继续活跃呢");
        }
//        [self.playerBack stop];
    });
}

@end
